package com.golxen.framework.netty.session.agent;


import com.golxen.framework.common.server.eServerType;
import com.golxen.utils.LogUtil;
import org.slf4j.Logger;

import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ServerClientReConnectHelper {

	private static final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);

	public static void tryConnect(ServerClientGroup client, int period) {
		TryConnectRunner tryRunner = new TryConnectRunner(client);
		ScheduledFuture<?> future = executor.scheduleAtFixedRate(tryRunner, period, period, TimeUnit.SECONDS);
		tryRunner.setFuture(future);
	}
}

class TryConnectRunner implements Runnable {
	private static Logger logger = LogUtil.COMMON;
	ScheduledFuture<?> future = null;
	ServerClientGroup client = null;

	public TryConnectRunner(ServerClientGroup client) {
		this.client = client;
	}

	public void setFuture(ScheduledFuture<?> future) {
		this.future = future;
	}

	public void run() {
		try {
			boolean result = false;
			//跨服有定时任务判断
			if (client.getServerType() == eServerType.CROSS || client.getServerType() == eServerType.CROSS2) {
				result = true;
			} else {
				result = client.reConnect();
			}

			if (result) {
				future.cancel(true);
			}
			logger.info("try connect to " + client.getServerType() + " server, address is " + client.getAddress() + ":"
					+ client.getPort() + (result ? " succeed" : " failed") + "." + (result ? "try connect exit." : ""));
		} catch (Exception e) {
			logger.error("try connect has exception:", e);
		}
	}
}
